package net.oschina.git.hikoyan.helloapi.async.flowcontrol;

import com.google.common.util.concurrent.RateLimiter;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by yan on 17/2/20.
 */
public class FlowControlMap {
    private static ConcurrentHashMap<String, Semaphore> cctDataMap = new ConcurrentHashMap<String, Semaphore>();
    private static ConcurrentHashMap<String, RateLimiter> qpsDataMap = new ConcurrentHashMap<String, RateLimiter>();

    static {
        //获取app的并发量
        FlowControlRule fcr = new FlowControlRule();
        fcr.setFlowControlKey("xingxingdache");
        fcr.setCctNum(1);
        fcr.setQpsNum(20);
        Set<FlowControlRule> data = new HashSet<FlowControlRule>();
        data.add(fcr);
        FlowControlMap.addFlowControlRules(data);

    }

    public static void addFlowControlRules(Set<FlowControlRule> data) {
        if (data == null || data.isEmpty()) {
            throw new RuntimeException("data不能为空, data=" + data);
        }

        for (FlowControlRule fcr : data) {
            if (fcr.getCctNum() > 0) {
                Semaphore semaphore = new Semaphore(fcr.getCctNum(), true);
                cctDataMap.put(fcr.getFlowControlKey(), semaphore);
            }
            if (fcr.getQpsNum() > 0) {
                if (fcr.getWarmupPeriod() > 0) {//预热模式
                    RateLimiter rateLimiter = RateLimiter.create(fcr.getQpsNum(), fcr.getWarmupPeriod(), TimeUnit.MILLISECONDS);
                    qpsDataMap.put(fcr.getFlowControlKey(), rateLimiter);
                } else {
                    RateLimiter rateLimiter = RateLimiter.create(fcr.getQpsNum());
                    qpsDataMap.put(fcr.getFlowControlKey(), rateLimiter);
                }

            }
        }
    }

    public static ConcurrentHashMap<String, Semaphore> getCctDataMap() {
        return cctDataMap;
    }

    public static ConcurrentHashMap<String, RateLimiter> getQpsDataMap() {
        return qpsDataMap;
    }
}
